package org.example.chat_room.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.catalina.session.StandardSession;
import org.example.chat_room.component.OnlineUserManager;
import org.example.chat_room.model.AddFriendRequest;
import org.example.chat_room.model.Friend;
import org.example.chat_room.model.FriendMapper;
import org.example.chat_room.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@RestController
public class FriendAPI {
    @Resource
    private FriendMapper friendMapper;

    @Autowired
    private OnlineUserManager onlineUserManager;

    private ObjectMapper objectMapper = new ObjectMapper();

    @GetMapping("/friendList")
    @ResponseBody
    public Object getFriendList(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if (session == null){
            System.out.println("[getFriendList] session 不存在！");
            return new ArrayList<Friend>();
        }
        User user = (User) session.getAttribute("user");
        if (user == null){
            System.out.println("[getFriendList] user 不存在！");
            return new ArrayList<Friend>();
        }
        int userId = user.getUserId();
        List<Friend> friends = friendMapper.selectFriendList(userId);
        return friends;
    }

    @GetMapping("/getFriendAvatar")
    public Object getFriendAvatar(HttpServletRequest request){
        HttpSession session = request.getSession();
        if (session == null){
            System.out.println("[getFriendAvatar] session 不存在！");
            return new ArrayList<Friend>();
        }
        User user = (User) session.getAttribute("user");
        if (user == null){
            System.out.println("[getFriendAvatar] user 不存在！");
            return new ArrayList<Friend>();
        }
        List<Friend> friends = friendMapper.selectFriendAvatarList(user.getUserId());
        return friends;
    }

    @GetMapping("/findFriend")
    @ResponseBody
    public Object findFiend(String name,HttpServletRequest request){
        try {
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute("user");
            return friendMapper.findFriend(user.getUserId(),name);
        }catch (NullPointerException e){
            e.printStackTrace();
        }
        return "";
    }

    @GetMapping("/addFriend")
    public Object addFriend(int friendId,String reason,HttpServletRequest request){
        try{
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute("user");
            System.out.println("[添加好友]"+user.getUserId()+", "+friendId+", "+reason);
//            写入数据库 -- 发送者的ID,接收方的ID，原因
            friendMapper.addFriendRequest(user.getUserId(),friendId,reason);
//            发送websocket响应
            WebSocketSession webSocketSession = onlineUserManager.getSession(friendId);
            if (webSocketSession != null){
                AddFriendRequest addFriendRequest = new AddFriendRequest();
                addFriendRequest.setType("addFriendRequest");
                addFriendRequest.setFromUserId(user.getUserId());
                addFriendRequest.setFromUserName(user.getUsername());
                addFriendRequest.setReason(reason);
//                给对应是用户方websocket请求，提示有用户尝试添加好友
                webSocketSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(addFriendRequest)));
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "";
    }

//    获取请求添加好友的信息
    @GetMapping("/getFrindRequest")
    @ResponseBody
    public Object getFriendRequest(HttpServletRequest request){
        List<AddFriendRequest> addFriendRequestList = new LinkedList<>();
        try {
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute("user");
//            要根据userId来找到有没有人发送给我添加好友的请求
            addFriendRequestList = friendMapper.getFriendRequest(user.getUserId());
        }catch (NullPointerException e){
            e.printStackTrace();
        }
        return addFriendRequestList;
    }

    @GetMapping("/acceptFriend")
    @ResponseBody
    @Transactional
    public Object acceptFriend(int friendId ,HttpServletRequest request){
        try {
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute("user");
//            1.删除好友请求表的存档
            friendMapper.deleteFriendRequest(friendId,user.getUserId());
//            2.修改好友表
            friendMapper.addFriend(friendId, user.getUserId());
//            3.通过websocket通知对方刷新好友列表
            WebSocketSession webSocketSession = onlineUserManager.getSession(friendId);
            if (webSocketSession != null){
                AddFriendRequest addFriendRequest = new AddFriendRequest();
                addFriendRequest.setType("acceptFriend");
                addFriendRequest.setFromUserId(user.getUserId());
                addFriendRequest.setFromUserName(user.getUsername());
                addFriendRequest.setReason("");
                webSocketSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(addFriendRequest)));
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "";
    }

    @GetMapping("/rejectFriend")
    @ResponseBody
    public Object rejectFriend(int friendId,HttpServletRequest request){
        try{
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute("user");
//            删除请求表的内容
            friendMapper.deleteFriendRequest(friendId,user.getUserId());
        } catch (NullPointerException e){
            e.printStackTrace();
        }

        return "";
    }

}
